/**
 * 
 */
package com.java.controller.admin;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane.IconifyAction;
import javax.validation.constraints.Pattern.Flag;

import org.apache.ibatis.javassist.expr.NewArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.java.entity.Good;
import com.java.entity.Order;
import com.java.entity.Payment;
import com.java.entity.User;
import com.java.service.impl.GoodServiceImpl;
import com.java.service.impl.ImageServiceImpl;
import com.java.service.impl.OrderServiceImpl;
import com.java.service.impl.PaymentServiceImpl;
import com.java.service.impl.UserServiceImpl;

/**
* @author Kidney
* 创建时间：2019年2月20日 下午5:51:46
* Description:
*/
/**
 * @author KIDNEY
 *
 */

@Controller
@RequestMapping("/user/")
public class PaymentController {

	@Autowired
	private GoodServiceImpl gsl;

	@Autowired
	private UserServiceImpl us;

	@Autowired
	private OrderServiceImpl os;

	@Autowired
	private PaymentServiceImpl ps;

	@RequestMapping("beforePay")
	public ModelAndView beforeCheck(HttpSession session, HttpServletRequest request, HttpServletResponse response) {

		ModelAndView mav = new ModelAndView();

		Map<Good, Integer> cart = (Map<Good, Integer>) session.getAttribute("cart");

		float sum = 0;
		float rate = (float) 0.05;

		if (cart != null) {
			for (Good key : cart.keySet()) {
				float days = cart.get(key);
				sum = key.getGoodPrice() * rate * days + sum;
				System.out.println(sum);
			}
		}

		float dSum = 0;
		System.out.println(cart);
		if (cart != null) {
			for (Good key : cart.keySet()) {
				System.out.println("key:"+ key.getGoodDepositNeed());
				dSum = key.getGoodDepositNeed() + dSum;
				
			}
		}

		Cookie[] cookies = request.getCookies();
		String username = null;

		for (Cookie cookie : cookies) {
			if (cookie.getName().equals("username")) {
				username = cookie.getValue();
			}
		}

		if (username != null) {
			User selectedUser = us.selectByName(username);
			int userId = selectedUser.getUserId();
			System.out.println(userId);
			float deposit = (float) selectedUser.getDeposit();
			System.out.println(deposit);
			if (deposit < sum) {
				mav.setViewName("/pages/deposit/recharge.jsp");// 押金充值
			}
			mav.getModel().put("selectedUser", selectedUser);
			mav.getModel().put("dSum", dSum);
			mav.getModel().put("sum", sum);
			mav.getModel().put("userId", userId);
			mav.getModel().put("cart", cart);
			mav.getModel().put("deposit", deposit);
			mav.getModel().put("total", sum + dSum);
			
			
			mav.getModel().put("address", selectedUser.getDizhi());
			mav.getModel().put("tele", selectedUser.getTele());	
			mav.getModel().put("name", selectedUser.getUserName());
			
			mav.setViewName("/pages/payment/payment.jsp");// 付款界面

		}
		return mav;
	}

	@RequestMapping("myPayment")
	@ResponseBody
	public ModelAndView getPayment( HttpServletRequest request) {	
		
		Cookie[] cookies = request.getCookies();


			String username = null;

			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("username")) {
					username = cookie.getValue();
				}
			}

			User selectedUser = us.selectByName(username);
			
			int selectedId = selectedUser.getUserId();
		List<Payment>	paymentList = ps.selectByUser(selectedId);
		ModelAndView mav = new ModelAndView();	
		mav.setViewName("/pages/front/orderManagement.jsp");// 付款成功界面
		mav.getModel().put("list", paymentList);
		
		
		return mav;
	}

	@RequestMapping("afterCheck")
	public ModelAndView afterCheck(HttpSession session, HttpServletRequest request, HttpServletResponse response,
			String address, String tele, int postcode, String name, Integer userId, Float sum, Float depostReturn) {
		ModelAndView mav = new ModelAndView();

		Payment payment = new Payment();
		payment.setAcmount(sum);
		payment.setAddress(address);
		payment.setDepositReturn(depostReturn);
		payment.setTele(tele);
		payment.setName(name);
		payment.setUserId(userId);
		payment.setPostcode(postcode);

		User user = us.selectByPrimaryKey(userId);
		float userDeposit = user.getDeposit();
		System.out.println(sum);
		System.out.println(depostReturn);
		float total = sum + depostReturn;
		float newUserDeposit = userDeposit - total;
		user.setDeposit(newUserDeposit);

		int flag0 = us.updateByPrimaryKeySelective(user);

		if (flag0 == 1) {
			int flag1 = ps.insertSelective(payment);

			if (flag1 == 1) {

				int flag2 = 0;
				Map<Good, Integer> cart = (Map<Good, Integer>) session.getAttribute("cart");
				for (Good key : cart.keySet()) {
					Order o = new Order();

					int days = cart.get(key);
					int goodId = key.getGoodId();
					int paymentId = ps.selectMaxId();
					Payment payment2 = ps.selectByPrimaryKey(paymentId);
					Date date = payment2.getCreateTime();

					Calendar calendar = new GregorianCalendar();
					calendar.setTime(date);
					calendar.add(Calendar.DATE, days);// 把日期往后增加一天.正数往后推,负数往前推
					date = calendar.getTime(); // 这个时间就是日期往后推一天的结果

					o.setDays(days);
					o.setOrderGood(goodId);
					o.setPaymentId(paymentId);
					o.setExpireDate(date);
					flag2 = os.insert(o);
					key.setGoodIfRent(true);
					gsl.updateByPrimaryKeySelective(key);
				}

				if (flag2 == 1) {
					mav.setViewName("/pages/payment/paymentSuccess.jsp");// 付款成功界面
					mav.getModel().put("status", "付款成功");
					mav.getModel().put("paymentId", ps.selectMaxId());
				}

			} else {
				mav.setViewName("/pages/payment/fail.jsp");
			}
		} else {
			mav.setViewName("/pages/payment/fail.jsp");
		}

		return mav;
	}

	@RequestMapping("test12")
	@ResponseBody
	public List<Payment> test23( HttpServletRequest request) {	
		
		Cookie[] cookies = request.getCookies();


			String username = null;

			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("username")) {
					username = cookie.getValue();
				}
			}
			
			
			User selectedUser = us.selectByName(username);
			System.out.println(selectedUser);
			int selectedId = selectedUser.getUserId();
			System.out.println(selectedId);
		List<Payment>	paymentList = ps.selectByUser(selectedId);

		
		
		return paymentList;
	}
}
